//
//  WebMainViewController.m
//  XTCloud
//
//  Created by QA on 2016/11/15.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "WebMainViewController.h"
#import <WebKit/WebKit.h>
#import "CLGifLoadView.h"
#import "YHWebViewProgressView.h"
#import "UIImage+Color.h"

#import "WKWebViewJavascriptBridge.h"
#import "WebViewController.h"

@interface WebMainViewController ()<WKNavigationDelegate>

@property WKWebViewJavascriptBridge* bridge;
@property (nonatomic, strong) WKWebView* webView;
@property (nonatomic, strong) CLGifLoadView * gifLoading;
@property (nonatomic, strong) YHWebViewProgressView *progressView;

@property (nonatomic, strong) NSString *webUrl;

@end

@implementation WebMainViewController

- (id)initWithUrl:(NSString*)webUrl
{
    self = [super init];
    if (self) {
        self.webUrl = webUrl;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initWKWebView];
}

- (void)dealloc
{
    //移除菜单权限获取注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    
    //去除黑色阴影线
    UIImage *image = [UIImage imageWithColor:[UIColor colorWithWhite:0.9 alpha:1] size:CGSizeMake(SuperWidth, 0.5)];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6){
        [self.navigationController.navigationBar setShadowImage:image];
    }
    
    //状态栏字体改变
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColorDispose colorWithHexString:@"#333333"], NSForegroundColorAttributeName,
                                                                     [UIFont systemFontOfSize:18.0], NSFontAttributeName, nil]];
}

- (void)initWKWebView
{
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.webView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_webView];
    
    [_webView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    // 创建进度条
    self.progressView = [[YHWebViewProgressView alloc] initWithFrame:CGRectMake(0, 41, CGRectGetWidth(self.view.bounds), 2.5)];
    _progressView.progressBarColor = [UIColor whiteColor];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
    [_progressView useWkWebView:self.webView];
    [self.navigationController.navigationBar addSubview:_progressView];
    
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
    [self jsFunctionHandle:_bridge];
    [_bridge setWebViewDelegate:self];
    
    //添加进度条
    self.gifLoading = [[CLGifLoadView alloc] initWithFrame:self.view.bounds];
    _gifLoading.backgroundColor = [UIColor clearColor];
    _gifLoading.hidden = YES;
    [self.view addSubview:_gifLoading];
    
    WebPushParameterModel *model = [[WebPushParameterModel alloc] init];
    model.URL = _webUrl;
    
    __weak WebMainViewController *viewController = self;
    __weak WebPushParameterModel *requestWeak = model;
    [_gifLoading setRetryBlcok:^{
        NSLog(@"页面重试");
        viewController.gifLoading.hidden = YES;
        [viewController loadURL:requestWeak];
    }];
    
    // 加载网页链接
    [self loadURL:model];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //清除进度条
    if(self.progressView) {
        _progressView.hidden = YES;
        [_progressView removeFromSuperview];
    }
}

- (void)jumpViewController:(WebPushParameterModel*)pushParameterModel
{
    NSInteger codeType = pushParameterModel.CodeType;
    
    //CodeType类型：0异常、1原生、2网页
    if (codeType == CodeTypeNative) {
        //            NativeViewController *viewController = [[NativeViewController alloc] init];
        //            [self.navigationController pushViewController:viewController animated:YES];
        
    } else if (codeType == CodeTypeWeb)  {
        WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:pushParameterModel];
        viewController.backResultDelagate = self;
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else {
        //            ErrorViewController *viewController = [[ErrorViewController alloc] init];
        //            [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark -
#pragma mark webview加载处理

- (void)loadURL:(WebPushParameterModel*)parameterModelURL
{
    // 加载网页链接
    if(parameterModelURL && parameterModelURL.URL){
        //转码url地址
        NSString *urlString = [parameterModelURL.URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //去除空格
        urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSURL *url = [NSURL URLWithString:urlString];
        //判断是否合法
        if(!url) [self.gifLoading setState:CLLoadStateFailed];
        else [_webView loadRequest:[NSURLRequest requestWithURL:url]];
        
    } else {
        [self.gifLoading setState:CLLoadStateFailed];
    }
}

#pragma mark -
#pragma mark JS跳转分发注册

- (void)jsFunctionHandle:(WKWebViewJavascriptBridge*)bridge
{
#pragma mark 跳转窗体
    [bridge registerHandler:@"Native_PushWindowCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_PushWindowCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
        
        //数据解析，并对数据完整性进行验证
        WebPushParameterModel *pushParameterModel = [WebPushParameterModel analysisJsonParameter:data];
        if (pushParameterModel == nil) return;
        [self jumpViewController:pushParameterModel];
        
    }];
    
#pragma mark 获取用户信息（简码、登陆信息）
    [bridge registerHandler:@"Native_GetUserInfoCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_CloseWindowCallback called: %@", data);
        ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        
        NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];
        [jsonDictionary setObject:model.briefCode forKey:@"CustomerCode"];//简码
        
        if ([NSJSONSerialization isValidJSONObject:jsonDictionary]){
            NSError *error;
            // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白，使输出更具可读性。
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            //返回页面参数
            responseCallback(json);
        }
    }];
}


#pragma mark WKNavigationDelegate

//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didStartProvisionalNavigation");
    //[self.gifLoading setState:CLLoadStateLoading];
}

//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didCommitNavigation");
    //[self.gifLoading setState:CLLoadStateFinish];
}

//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didFinishNavigation");
    [self.gifLoading setState:CLLoadStateFinish];
}

//页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"didFailProvisionalNavigation:%@",error);
    [self.gifLoading setState:CLLoadStateFailed];
    self.gifLoading.hidden = NO;
}

//导航错误 404,403,500
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"didFailProvisionalNavigation:%@",error);
    [self.gifLoading setState:CLLoadStateFailed];
    self.gifLoading.hidden = NO;
}

#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    //Reload通知页面刷新
    [_bridge callHandler:@"JS_PopBackCallback" data:backValue responseCallback:^(id response) {
        NSLog(@"JS_PopBackCallback responded: %@", response);
    }];
}

#pragma mark UIButtonEvent

- (void)renderButtons:(WKWebView*)webView {
    UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
    
    UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [callbackButton setTitle:@"Call handler" forState:UIControlStateNormal];
    [callbackButton addTarget:self action:@selector(callHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:callbackButton aboveSubview:webView];
    callbackButton.frame = CGRectMake(10, 400, 100, 35);
    callbackButton.titleLabel.font = font;
    
    UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [reloadButton setTitle:@"Reload webview" forState:UIControlStateNormal];
    [reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:reloadButton aboveSubview:webView];
    reloadButton.frame = CGRectMake(110, 400, 100, 35);
    reloadButton.titleLabel.font = font;
}

- (void)callHandler:(id)sender {
    id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
    [_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];
}

- (void)loadExamplePage:(WKWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"ExampleApp" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [webView loadHTMLString:appHtml baseURL:baseURL];
}

#pragma mark -
#pragma mark IBAction


@end
